<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Upload;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Filesystem;
/**
 * 示例接口 
 */
class Excel extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getcasesexcelbyid'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 生成出库信息 Excel 文件
     */
    public function index()
    {

            // 获取请求参数中的 id
            $id = $this->request->param('id');

            // 验证 id 是否有效
            if (empty($id)) {
                $this->error('缺少必要参数 id');
                return;
            }

            // 查询快递信息
            $info = Db::name('aa_kuaidi')->where(['id' => $id])->find();

            // 检查快递信息是否存在
            if (empty($info)) {
                $this->error('未找到对应的快递信息');
                return;
            }

        $list = Db::name('aa_kuaidi_log')->where(['kid' => $id])->select();

// 收集所有需要查询的 order ID
        $orderIds = array_column($list, 'order');

// 批量查询照片日志
        $photoLogs = Db::table('cmf_newphoto')->whereIn('id', $orderIds)->select();




        $photoLogMap = [];
        foreach ($photoLogs as $log) {
            $photoLogMap[$log['id']] = $log;
        }

// 收集所有需要查询的 case ID
        $caseIds = array_column($photoLogs, 'caseid');

// 批量查询案例信息
        $cases = Db::name('aa_case')->whereIn('id', $caseIds)->select();
        $caseMap = [];
        foreach ($cases as $case) {
            $caseMap[$case['id']] = $case;
        }

// 收集所有需要查询的 merch ID
        $merchIds = array_column($cases, 'merch');

// 批量查询商家信息
        $merchs = Db::name('aa_merch')->whereIn('id', $merchIds)->select();
        $merchMap = [];
        foreach ($merchs as $merch) {
            $merchMap[$merch['id']] = $merch;
        }



        $arr = [];
        foreach ($list as $key) {
            $dd = $photoLogMap[$key['order']] ?? [];



            if (!empty($dd)) {
                $case = $caseMap[$dd['caseid']] ?? [];
                $merch = $merchMap[$case['merch']] ?? [];


                $dds['logo']=$merch['title'];
                $dds['code']=$dd['code'].'  ';
                $dds['sku']=$dd['sku'];
                $dds['color']=$dd['color2'].'/'.$dd['color1'];
                $dds['size']=$dd['size'];
                $dds['name']=$key['user'];
                $dds['kd']=$info['order'];
                $dds['title']=$case['title'];
                $dds['desc']=$info['desc'];

                $arr[] = $dds;
            }
        }




        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:I1');
        $sheet->setCellValue('A1', $arr[0]['logo'] ." ". date('Y-m-d',$info['time']) ." 出货信息");
        // 设置表头
        $headers = ['品牌', '条码', 'sku', '颜色','尺码','操作人','快递单号','批次','备注'];
        $column = 'A';
        foreach ($headers as $header) {
            $sheet->setCellValue($column.'2', $header);
            $column++;
        }



        // 填充数据
        $row = 3;
        foreach ($arr as $item) {
            $column = 'A';
            foreach ($item as $value) {
                $sheet->setCellValue($column.$row, $value);
                $column++;
            }
            $row++;
        }

        // 创建 Xlsx 写入器
        $writer = new Xlsx($spreadsheet);

        // 指定保存目录，这里以项目的 public 目录下的 excel 文件夹为例
        $savePath = "./upload/excel/";

        // 确保目录存在

        $savePathb = "/upload/excel/";
        // 生成文件名
        $fileName = $arr[0]['logo'].date('Y-m-d').'退仓.xlsx';

        $fullPath = $savePath . $fileName;

        // 保存 Excel 文件到指定目录
        $writer->save($fullPath);





        $fiel= cdnurl($savePathb.$fileName,true);

        $this->success('',$fiel);
        // 返回文件保存成功的信息



    }


    /**
     * 生成上传用 Excel 文件
     */
    public function getcasesexcelbyid()
    {
        $id = $this->request->param('id');



    }





}
